import { deleteNodeAndChildren, reactDndTypes } from "@/utils/reactDnd/reactDnd";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

 interface BoxItem {
  id: string;
  type: string;
  content?: string;
  // 根据您的实际数据结构添加其他属性
  [key: string]: any;
}

 interface NowData {
  id: string;
  // 其他属性...
  [key: string]: any;
}
// 新增EndData接口，明确endData的结构
interface EndData {
  item?: { id: string; [key: string]: any };
  parentId?: string;
  isOver?: boolean;
}
 interface LastHoverData {
  id: string;
  // 其他可能的属性
  [key: string]: any;
}

 interface ReactDndState {
  boxData: Record<string, BoxItem>;
  boxIndex: Record<string, any>;
  lastHoverData: LastHoverData | null;
  nowData: NowData | null;
  endData: EndData |null;
}

const initialState:ReactDndState = {
    boxData: {},
    boxIndex: {},
    lastHoverData: null,
    nowData: null,
    endData:null
    
}
const reacrtDndSlice = createSlice({
    name: 'reactDnd',
    initialState,
    reducers: {
        // 直接更新最新获取的数据
        updateApiData(state, { payload: positionData }) {
            state.boxData = positionData.boxDataStore;
            state.boxIndex = positionData.boxIndexStore;
        },
        // 储存最后一次数据
        addlastHoverData(state, { payload: positionData }) {
            state.lastHoverData = positionData;
        },
        // 点击存当前的数据
        addNowData(state, { payload: positionData }) {
            state.nowData = positionData;
        },

        addComponent(state, { payload: { item, parentId } }) {
            console.log('666')
            state.boxIndex[parentId] = [...(state.boxIndex[parentId] || []), item.id];
            state.boxData[item.id] = { ...item, parentId };

        },
        addComponentRow(state, { payload: { item, parentId } }) {
            state.boxIndex[parentId] = [...(state.boxIndex[parentId] || []), item.id];
            state.boxData[item.id] = { ...item, parentId };

        },
        // 更新对应数据
        updataComponent(state, { payload: positionData }) {
            state.boxData[positionData.id] = positionData;
        },
        moveComponent(state, { payload: { item, parentId } }) {
            if (state.boxData[item.id]) {
                state.boxIndex[item.parentId] = state.boxIndex[item.parentId].filter((it: string) => it !== item.id);
            }
        },
        deleteComponent(state, { payload: { newDataTable, newIndexTable } }) {
            console.log("boxData,boxIndex", newDataTable, newIndexTable)
            state.boxData = newDataTable || {}
            state.boxIndex = newIndexTable || {}

        },
        SwperIndex(state, { payload: { item, parentId, insertPosition } }) {
            const currentItems = state.boxIndex[item.parentId] || [];
            const parentIndex = currentItems.indexOf(parentId);
            const itemIndex = currentItems.indexOf(item.id);
            // 如果 parentId 或 item.id 不存在，直接返回
            if (parentIndex === -1 || itemIndex === -1) return;

            // 先移除 item
            currentItems.splice(itemIndex, 1);

            // 计算新的插入位置
            let newIndex;
            // if (insertPosition === 'after') {
            //     newIndex = parentIndex + 1; // 插入到 parentId 下方
            // } else if (insertPosition === 'before') {
            newIndex = parentIndex; // 插入到 parentId 上方
            // }

            // 插入到新位置
            currentItems.splice(newIndex, 0, item.id);

            state.boxIndex[item.parentId] = currentItems;
        },
        endDataComponent(state, { payload: { item, parentId, isOver } }) {
            state.endData = { ...state.endData, item, parentId }
        },
    },

    extraReducers: (builder) => {

    }
})

export const { updateApiData,addComponent, addComponentRow, moveComponent, SwperIndex, addlastHoverData, addNowData, updataComponent, deleteComponent } = reacrtDndSlice.actions
export const setBoxData = createAsyncThunk("React/dnd",
    async ({ item, monitor, parentId }: { item: any, monitor: any, parentId?: string }, thunkAPI) => {
        try {
            if (!monitor.isOver({ shallow: true })) return //鼠标在容器内触发
            if (monitor.didDrop()) return;
            const state = thunkAPI.getState() as any;
            const boxIndex = state?.reactDnd.boxIndex || {};
            // 如果拖动的，已经添加过了就不要添加了更新了
            if (boxIndex[parentId as string]?.includes(item.id) && item.parentId == parentId) return
            // 如果父ID不同代表挪动了位置，要删除原来的组件位置，然后再添加
            if (item.parentId !== parentId) {
                thunkAPI.dispatch(moveComponent({ item, parentId }))
            }
            item.targetId = monitor.targetId
            if (item.type === reactDndTypes.ROW) {
                const dataRow = [{ ...item, parentId }]
                dataRow.push({ id: Date.now().toString(), targetId: monitor.targetId, type: reactDndTypes.COL, parentId: item.id, span: 12, offset: 0, push: 0 })
                dataRow.push({ id: Date.now().toString() + 1, targetId: monitor.targetId, type: reactDndTypes.COL, parentId: item.id, span: 12, offset: 0, push: 0 })
                console.log("dataRow", dataRow)
                dataRow.forEach((item) => {
                    thunkAPI.dispatch(addComponent({ item, parentId: item.parentId }))
                })
            } else {
                thunkAPI.dispatch(addComponent({ item, parentId }))
            }

        } catch (error) {
            console.log(error, 'error')
        }
    })
export const deleteBox = createAsyncThunk("React/deleteDnd",
    async ({ Id }: { Id: string }, thunkAPI) => {
        try {
            console.log("Id", Id)
            const state = thunkAPI.getState() as any;
            const boxIndex = state?.reactDnd.boxIndex || {};
            const boxData = state?.reactDnd.boxData || {};
            const { newDataTable, newIndexTable } = deleteNodeAndChildren(boxData, boxIndex, Id);
            console.log(newDataTable, newIndexTable)
            thunkAPI.dispatch(deleteComponent({ newDataTable, newIndexTable }))


        } catch (error) {
            console.log(error, 'error')
        }
    })
export const setSwperIndex = createAsyncThunk("React/dnd",
    async ({ item, parentId, insertPosition }: { item: any, parentId?: string, insertPosition: "after" | "before" }, thunkAPI) => {
        try {
            thunkAPI.dispatch(SwperIndex({ item, parentId, insertPosition }))
        } catch (error) {
            console.log(error, 'error')
        }
    })


export default reacrtDndSlice.reducer
